import logging

import pytest

from resource.pom.hap import Hap
from resource.pom.settings import Settings
from utils.manager import Images


@pytest.fixture(autouse=True)
def uninstall_hap(device):
    logging.info('预置条件：镜像版本正确、联网正常，浏览器hap安装正常')
    device.install_hap(Hap.package_path)
    connect_status = Settings.connect_wifi(device)
    assert connect_status, 'wifi连接失败'
    yield
    try:
        device.uninstall_hap(Hap.bundle_name)
    except:
        pass


class Test:
    app = Hap

    # 1.打开demo
    # 2.双指放大缩小百度网页，有结果1
    # 3.demo中的百度页面搜索选择微博
    # 4.分别抛滑漫滑微博网页，有结果2
    # 1.双指放大缩小功能正常,无crash生成
    # 2.抛滑漫滑功能正常，无crash生成

    @pytest.mark.parametrize('setup_teardown', [app.bundle_name], indirect=True)
    def test(self, setup_teardown, device):
        p0 = (300, 500)
        p1 = (200, 500)
        p2 = (400, 500)
        p3 = (500, 500)
        logging.info('步骤1.打开浏览器')
        device.start_ability(self.app.bundle_name, self.app.ability_name)
        device.wait(5)
        logging.info('步骤2.双指放大缩小百度网页，有结果1')
        device.hdc_shell('rm -rf /data/log/faultlog/temp/*')
        # 双指放大
        device.pinch_with_both_fingers(p0, p1, p2, p3)
        pinch_out_log = device.hdc_shell('ls -l /data/log/faultlog/temp/')
        pinch_out = device.save_snapshot_to_local('pinch_out.jpeg')
        Images.crop_picture(pinch_out)

        device.hdc_shell('rm -rf /data/log/faultlog/temp/*')
        # 双指缩小
        device.pinch_with_both_fingers(p1, p0, p3, p2)
        pinch_in_log = device.hdc_shell('ls -l /data/log/faultlog/temp/')
        pinch_in = device.save_snapshot_to_local('pinch_in.jpeg')
        Images.crop_picture(pinch_in)

        logging.info('预期结果1.双指放大缩小功能正常,无crash生成')
        assert pinch_out_log == 'total 0', '首页放大有crash'
        assert pinch_in_log == 'total 0', '首页缩小有crash'
        s1 = Images.compare_image_similarity(pinch_out, self.app.main_page_pinch_out)
        s2 = Images.compare_image_similarity(pinch_in, self.app.main_page)
        assert s1 > 0.8, '双指放大效果可能有问题'
        assert s2 > 0.8, '双指捏合缩小可能有问题'

        logging.info('步骤3.demo中的百度页面搜索选择微博')
        device.refresh_layout()
        device.click_element(device.get_element_by_text('weibo'))
        device.wait(5)
        device.click(*self.app.refresh_btn)
        device.wait(10)
        logging.info('步骤4.分别抛滑漫滑微博网页，有结果2')
        device.hdc_shell('rm -rf /data/log/faultlog/temp/*')
        device.swipe(360, 640, 360, 500)
        device.fling(360, 640, 360, 500)
        swipe_log = device.hdc_shell('ls -l /data/log/faultlog/temp/')
        logging.info('预期结果2.抛滑漫滑功能正常，无crash生成')
        assert swipe_log == 'total 0', '微博页面抛滑慢滑有crash'
